package org.lmind.example.common.service.mail;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.lmind.example.common.core.UnhandledException;

public class DefaultMailService {
	
	private String host;
	
	private String user;
	
	private String password;
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	Mail createMail() {
		return new Mail();
	}

	void sendMail(Mail mail, String from, String to) {
		try {
			Session session = createSession();
			Message msg = new MimeMessage(createSession());
			msg.setFrom(new InternetAddress(from));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
			msg.setSubject(mail.getSubject());
			msg.setSentDate(new Date());
			msg.setContent(mail.createMimeMultipart());
			
			Transport transport = session.getTransport("smtp");
			transport.connect(host, user, password);
			transport.sendMessage(msg, msg.getAllRecipients());
		} catch (AddressException e) {
			throw new UnhandledException(e);
		} catch (MessagingException e) {
			throw new UnhandledException(e);
		}
	}
	
	protected Session createSession() {
		
		Properties prop = new Properties();
		if (user != null || password != null)
			prop.put("mail.smtp.auth", "true");
		
		Session session = Session.getDefaultInstance(prop);
		return session;
	}
}
